package com.fjec.base.schedule.handler;

import com.fjec.base.entity.SysAnnex;
import com.fjec.base.mapper.SysAnnexMapper;
import com.fjec.base.service.ISysAnnexService;
import com.fjec.common.schedule.BaseScheduleHandler;
import com.fjec.common.util.JsonUtil;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class DelAnnexHandler extends BaseScheduleHandler {

    @Resource
    private ISysAnnexService sysAnnexService;

    public String handle(int limit, int days) {
        List<Map<String, Object>> errorList = new ArrayList<>();
        // 查询创建时间为days之前，并删除标记为1的附件数据
        List<SysAnnex> entityList = sysAnnexService.getAnnexForDelete(limit, days);
        int success = 0;
        for(SysAnnex entity : entityList) {
            try {
                sysAnnexService.physicalDeleteAnnex(entity);
                success++;
            } catch (Exception ex) {
                String guid = this.error(ex);
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("guid", guid);
                errorMap.put("id", entity.getId());
                errorList.add(errorMap);
            }
        }
        String result;
        if (errorList.isEmpty()) {
            // 全部处理，无异常
            result = String.format("Handle delete annex num:[%d]", success);
        } else {
            result = String.format("Handle delete annex success num:[%d], fail:[%d], Ids:[%s]",
                    success, errorList.size(), JsonUtil.toJson(errorList));
        }
        return result;
    }
}
